package com.sparkflow.mysqlbinlog.clickhousesync.config.datasource;

import com.sparkflow.mysqlbinlog.clickhousesync.config.properties.ClickHouseProperties;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
import ru.yandex.clickhouse.ClickHouseDataSource;

import javax.sql.DataSource;

/**
 * 数据源配置类
 * 管理MySQL和ClickHouse数据库连接配置
 *
 * @author Mr_xiaoZH
 * @date 2025-07-23
 */
@Configuration
public class DataSourceConfig {

    @Autowired
    private ClickHouseProperties clickHouseProperties;
    @Autowired
    private DataSourceProperties dataSourceProperties;

    @Primary
    @Bean(name = "mysqlDataSource")
    public DataSource mysqlDataSource() {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl(this.dataSourceProperties.getUrl());
        dataSource.setUsername(dataSourceProperties.getUsername());
        dataSource.setPassword(dataSourceProperties.getPassword());
        dataSource.setDriverClassName(dataSourceProperties.getDriverClassName());
        return dataSource;
    }

    @Bean
    @Primary
    public JdbcTemplate mysqlJdbcTemplate(@Qualifier("mysqlDataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    @Bean
    public ClickHouseDataSource clickHouseDataSource() {
        ru.yandex.clickhouse.settings.ClickHouseProperties properties = new ru.yandex.clickhouse.settings.ClickHouseProperties();
        properties.setUser(clickHouseProperties.getUser());
        properties.setPassword(clickHouseProperties.getPassword());
        properties.setSocketTimeout(clickHouseProperties.getConnection().getSocketTimeout());
        properties.setConnectionTimeout(clickHouseProperties.getConnection().getConnectionTimeout());
        properties.setCompress(clickHouseProperties.getConnection().isCompress());
        properties.setBufferSize(clickHouseProperties.getConnection().getBufferSize());
        properties.setMaxExecutionTime(clickHouseProperties.getConnection().getMaxExecutionTime());
        properties.setMaxThreads(clickHouseProperties.getConnection().getMaxThreads());

        return new ClickHouseDataSource(clickHouseProperties.getUrl(), properties);
    }

    @Bean(name = "clickHouseJdbcTemplate")
    public JdbcTemplate clickHouseJdbcTemplate(@Qualifier("clickHouseDataSource") DataSource clickHouseDataSource) {
        return new JdbcTemplate(clickHouseDataSource);
    }
}
